---
title: 'Cross Origin Testing: Cypress Guide'
description: 'Learn how to test cross-origin content with Cypress.'
sidebar_label: Cross Origin Testing
e2eSpecific: true
---

<ProductHeading product="app" />

# Cross Origin Testing

:::info

##### <Icon name="question-circle" color="#4BBFD2" /> What you'll learn

- What strategies Cypress uses to work around same-origin policy
- Limitations and workarounds with cross-origin content

:::

## Web Security

Browsers adhere to a strict
[same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).
This means that browsers restrict access between `<iframes>` when their origin
policies don't match.

Because Cypress works from within the browser, Cypress must be able to directly
communicate with your remote application at all times. Unfortunately, browsers
naturally try to prevent Cypress from doing this.

To get around these restrictions, Cypress implements some strategies involving
JavaScript code, the browser's internal APIs, and network proxying to _play by
the rules_ of same-origin policy. It's our goal to fully automate the
application under test without you needing to modify your application's code -
and we are _mostly_ able to do this.

### What Cypress does under the hood

- Proxies all HTTP / HTTPS traffic.
- Changes the hosted URL to match that of the application under test.
- Uses the browser's internal APIs for network level traffic.

When Cypress first loads, the internal Cypress web application is hosted on a
random port: something like `http://localhost:64874/__/`.

After the first [`cy.visit()`](/api/commands/visit) command is issued in a test,
Cypress changes its URL to match the origin of your remote application, thereby
solving the first major hurdle of same-origin policy. Your application's code
executes the same as it does outside of Cypress, and everything works as
expected.

:::info

<strong>How is HTTPS supported?</strong>

Cypress must assign and manage browser certificates to be able to
modify the traffic in real time. You'll notice Chrome display a warning that the 'SSL certificate does not
match'. This is expected behavior. Under the hood we act as our own CA
authority and issue certificates dynamically in order to intercept requests
otherwise impossible to access. We only do this for the origin currently
under test, and bypass other traffic.

Note, that Cypress allows you to optionally specify CA / client certificate
information for use with HTTPS sites. See
[configuring client certificates](/app/references/client-certificates). If
the remote server requests a client certificate for a configured URL, Cypress
will supply it.

:::

## Limitations

It's important to note that although we do our **very best** to ensure your
application works normally inside of Cypress, there _are_ some limitations you
need to be aware of.

- [Different origins per test require cy.origin()](#Different-origins-per-test-require-cyorigin)
- [Cross-origin iframes are not supported](#Cross-origin-iframes)
- [Navigating from HTTPS to HTTP will error](#Insecure-Content)
- [Cypress requires that the URLs navigated to have the same port](#Same-port-per-test)

### Different origins per test require `cy.origin()`

Cypress changes its own host URL to match that of your applications. With the
exception of `cy.origin`, Cypress requires that the URLs navigated to have the
same [origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) for the
entirety of a single test.

If you attempt to visit two different origins, the `cy.origin` command must
be used to wrap Cypress commands of the second visited domain. Otherwise,
Cypress commands will timeout after the navigation and will eventually error.
This is because the commands that were expected to run on the second domain are
actually being run on the first domain.

Without `cy.origin()`, you can visit different origins in _different_ tests,
but not in the _same_ test.

#### Examples of test cases that will error without the use of `cy.origin`

1. [`.click()`](/api/commands/click) an `<a>` with an `href` to a different
   origin with subsequent Cypress commands being run.
2. [`.submit()`](/api/commands/submit) a `<form>` that causes your web server to
   redirect you to a different origin where additional Cypress commands are
   run.
3. Issue a JavaScript redirect in your application, such as
   `window.location.href = '...'`, which navigates to a different origin
   where additional Cypress commands are run.

In each of these situations, Cypress will lose the ability to automate your
application and will error via command timeout unless the `cy.origin` command is
used.

Read on to learn about
[working around these common problems](#Common-Workarounds).

<DocumentDomainWorkaround />

#### Parts of a URL

We understand this is a bit complicated to understand, so we have built a nifty
chart to help clarify the differences!

<DocsImage
  src="/img/app/cross-origin-testing/parts_of_a_url.jpg"
  alt="Diagram showing the parts of a URL including href broken into protocol, host, pathname, hash and smaller components of hostname, port, path, and search with and example URL"
/>

##### Origin

An `origin` is comprised of a URL's `scheme`, `hostname`, _and_ `port`. Given the URLs
below, all have the same origin compared to `https://www.cypress.io`:

- `https://www.cypress.io/cloud`
- `https://www.cypress.io/app`

But the following have different origins compared to `https://www.cypress.io`:

- `http://www.cypress.io` (different `scheme`)
- `https://docs.cypress.io` (different `hostname` due to the subdomain)
- `https://www.auth0.com` (different `hostname`)
- `https://www.cypress.io:81` (different `port`)

:::danger

<Icon name="exclamation-triangle" color="red" /> You **cannot** [visit](/api/commands/visit)
two different origins in the same test and continue to interact with the page without
the use of the [`cy.origin()`](/api/commands/origin) command.

:::

:::tip

<Icon name="check-circle" color="green" /> You **can** [visit](/api/commands/visit)
two or more origins in **different** tests without needing [`cy.origin()`](/api/commands/origin).
:::

For practical purposes, this means the following:

```javascript
// This test will run without error
it('navigates', () => {
  cy.visit('https://www.cypress.io')
  cy.visit('https://www.cypress.io/app')
  cy.get('selector') // yup all good
})
```

```javascript
// this will error because the origin https://docs.cypress.io doesn't match the origin https://www.cypress.io
it('navigates', () => {
  cy.visit('https://www.cypress.io')
  cy.visit('https://docs.cypress.io')
  cy.get('selector')
})
```

To fix the above cross-origin error, use `cy.origin()` to indicate which origin
the sequential command should run against:

```javascript
it('navigates', () => {
  cy.visit('https://example.cypress.io')
  cy.visit('https://docs.cypress.io')
  cy.origin('https://docs.cypress.io', () => {
    cy.get('selector') // yup all good
  })
})
```

```javascript
it('navigates', () => {
  cy.visit('https://www.cypress.io')
})

// split visiting different origin in another test
it('navigates to new origin', () => {
  cy.visit('https://cypress-dx.com')
  cy.get('selector') // yup all good
})
```

### Cross-origin iframes

If your site embeds an `<iframe>` that is a cross-origin frame, Cypress won't
be able to automate or communicate with this `<iframe>`.

#### Examples of uses for cross-origin iframes

- Embedding a Vimeo or YouTube video.
- Displaying a credit card form from Stripe or Braintree.
- Displaying an embedded login form from Auth0.
- Showing comments from Disqus.

If you'd like support for this
(check our [open issue](https://github.com/cypress-io/cypress/issues/136)), or
you can
[disable web security](/app/guides/cross-origin-testing#Disabling-Web-Security).

### Insecure Content

Because of the way Cypress is designed, if you're testing an HTTPS site,
Cypress will error anytime you attempt to navigate back to an HTTP site. This
behavior helps highlight a _pretty serious security problem_ with your
application.

#### Example of accessing insecure content

```javascript title="test.cy.js"
cy.visit('https://example.cypress.io')
```

In your application code, you set `cookies` and store a session on the browser.
Now let's imagine you have a single `insecure` link (or JavaScript redirect) in
your application code.

```html title="index.html"
<html>
  <a href="http://example.cypress.io/page2">Page 2</a>
</html>
```

Cypress will immediately fail with the following test code:

```javascript title="test.cy.js"
cy.visit('https://example.cypress.io')
cy.get('a').click() // will fail
```

Browsers refuse to display insecure content on a secure page. Because Cypress
initially changed its URL to match `https://example.cypress.io` when the browser
followed the `href` to `http://example.cypress.io/page2`, the browser will
refuse to display the contents.

Now you may be thinking, _This sounds like a problem with Cypress because when I
work with my application outside of Cypress it works just fine._

However, the truth is, Cypress is exposing a _security vulnerability_ in your
application, and you _want_ it to fail in Cypress.

`cookies` that don't have their `secure` flag set to `true` will be sent as
clear text to the insecure URL. This leaves your application vulnerable to
session hijacking.

This security vulnerability exists **even if** your web server forces a
`301 redirect` back to the HTTPS site. The original HTTP request was still made
once, exposing insecure session information.

#### The solution

Update your HTML or JavaScript code to not navigate to an insecure HTTP page and
instead only use HTTPS. Additionally make sure that cookies have their `secure`
flag set to `true`.

If you're in a situation where you don't control the code, or otherwise cannot
work around this, you can bypass this restriction in Cypress by
[disabling web security](/app/guides/cross-origin-testing#Disabling-Web-Security).

### Same port per test

Cypress requires that the URLs navigated to have the same port (if specified)
for the entirety of a single test. This matches the behavior of the browser's
normal
[same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).

## Common Workarounds

Let's investigate how you might encounter cross-origin errors in your test code
and break down how to work around them in Cypress.

### External Navigation

The most common situation where you might encounter this error is when you click
on an `<a>` that navigates to another origin.

```html title="index.html"
<html>
  <a href="https://example.cypress.io">Cypress</a>
</html>
```

```javascript title="test.cy.js"
cy.visit('http://localhost:8080') // where your web server + HTML is hosted
cy.get('a').click() // browser navigates to https://cypress.io
cy.get('selector').should('exist') // Cypress errors
```

:::warning

We don't recommend visiting an origin that you don't control in your tests
which you can read more about
[here](/app/core-concepts/best-practices#Visiting-External-Sites)

:::

If you control this origin, either by owning the hosted instance
or by other means, we recommend testing this origin with `cy.origin`.

```javascript title="test.cy.js"
cy.visit('http://localhost:8080') // where your web server + HTML is hosted
cy.get('a').click() // browser navigates to https://example.cypress.io
cy.origin('https://example.cypress.io', () => {
  // declare cy.origin command on expected domain
  cy.get('selector').should('exist') // Yup all good
})
```

If you're not in control of this origin, we recommend you test that the `href`
property is correct instead of performing the navigation. This will help lead to
more deterministic tests.

```javascript
// this test verifies the behavior and will run considerably faster
cy.visit('http://localhost:8080')
cy.get('a').should('have.attr', 'href', 'https://example.cypress.io') // no page load!
```

If for any reason the two above methods cannot be used,
[`cy.request()`](/api/commands/request) may be an option to verify content as
`cy.request()` is _NOT bound to CORS or same-origin policy_.

```javascript
cy.visit('http://localhost:8080')
cy.get('a').then(($a) => {
  // pull off the fully qualified href from the <a>
  const url = $a.prop('href')

  // make a cy.request to it
  cy.request(url).its('body').should('include', '</html>')
})
```

### Form Submission Redirects

When you submit a regular HTML form, the browser will follow the HTTP(s)
request.

```html title="index.html"
<html>
  <form method="POST" action="/submit">
    <input type="text" name="email" />
    <input type="submit" value="Submit" />
  </form>
</html>
```

```javascript title="test.cy.js"
cy.visit('http://localhost:8080')
cy.get('form').submit() // submit the form!
```

If your back end server handling the `/submit` route does a `30x` redirect to a
different origin, you'll need to use the `cy.origin` command if running
additional Cypress commands after submitting the form.

```javascript title="routes.js"
// node / express code on localhost:8080 server
app.post('/submit', (req, res) => {
  // redirect the browser to cypress.io
  res.redirect('https://example.cypress.io')
})
```

You can test this with `cy.origin`, which may look like the following test case:

```javascript title="test.cy.js"
cy.visit('http://localhost:8080')
cy.get('form').submit() // submit the form!
cy.origin('cypress.io', () => {
  cy.url().should('contain', 'cypress.io')
})
```

A common use case for this is Single sign-on (SSO), OAuth, Open ID Connect
(OIDC), or Authentication as a Service platforms, such as [Auth0](/app/guides/authentication-testing/auth0-authentication),
[Okta](/app/guides/authentication-testing/okta-authentication), [Amazon
Cognito](/app/guides/authentication-testing/amazon-cognito-authentication), and others.

In these situations, if controlling the domain under test, we recommend that you
test these with `cy.origin`.

```javascript title="test.cy.js"
cy.visit('http://localhost:8080')
cy.get('#login').click() // click a login button, which takes us to our authentication page.
cy.origin('cypress.io', () => {
  cy.get('#username').type('User1')
  cy.get('#password').type('Password123')

  // prompts a sign in that redirects to http://localhost:8080 with a token, cookie, or other means of acknowledgement
  cy.get('button').contains('Sign In').click()
})

cy.get('#user-name-welcome').should('equal', 'Welcome, User1!')
```

If for any reason you can't leverage `cy.origin`, programmatic authentication
is still an option. In this situation you may `POST` to a different server and
are redirected elsewhere (typically with the session token in the URL). If
that's the case, you can still test this behavior with
[`cy.request()`](/api/commands/request).

In fact we can likely bypass the initial visit altogether and `POST` directly to
your SSO server.

```javascript
cy.request('POST', 'https://sso.corp.com/auth', {
  username: 'foo',
  password: 'bar',
}).then((response) => {
  // pull out the location redirect
  const loc = response.headers['Location']

  // parse out the token from the url (assuming its in there)
  const token = parseOutMyToken(loc)

  // do something with the token that your web application expects
  // likely the same behavior as what your SSO does under the hood
  // assuming it handles query string tokens like this
  cy.visit('http://localhost:8080?token=' + token)

  // if you don't need to work with the token you can sometimes
  // visit the location header directly
  cy.visit(loc)
})
```

### JavaScript Redirects

When we say JavaScript Redirects we are talking about any kind of code that does
something like this:

```html title="index.html"
<html>
  <button id="nav">Navigate to Cypress example</button>
  <script>
    document.querySelector('#nav').addEventListener('click', () => {
      window.location.href = 'https://example.cypress.io'
    })
  </script>
</html>
```

You can test this with `cy.origin`, which may look like the following test case:

```javascript title="test.cy.js"
cy.visit('http://localhost:8080')
cy.get('#nav').submit() // trigger a javascript redirect!
cy.origin('https://example.cypress.io', () => {
  cy.url().should('contain', 'cypress.io')
})
```

### Cross-Origin Errors with `cy.origin`

Sometimes, when using `cy.origin` and especially with websites that are not
under your immediate test control, cross-origin errors may still tend to creep
up. We don't recommend visiting or interacting with sites you
[do not control](/app/core-concepts/best-practices#Visiting-External-Sites).
However, if this is necessary, most of these issues can usually be remedied by
applying` the
[modify obstructive third-party code](/app/references/experiments#Configuration)
experimental flag or by
[disabling web security](/app/guides/cross-origin-testing#Disabling-Web-Security).

## Disabling Web Security

So if you cannot work around any of the issues using the suggested workarounds
above, including
[modifying obstructive third-party code](/app/guides/cross-origin-testing#Modifying-Obstructive-Third-Party-Code)
with `cy.origin`, you may want to disable web security.

One last thing to consider here is that every once in a while we discover bugs
in Cypress that lead to cross-origin errors that can otherwise be fixed. If you
think you're experiencing a bug,
[open an issue](https://github.com/cypress-io/cypress/issues/new/choose).

:::caution

<strong>Chrome only</strong>

Disabling web security is only supported in Chrome-based browsers. Settings in
`chromeWebSecurity` will have no effect in other browsers. We will log a warning
in this case.

<DocsImage
  src="/img/app/web-security/chrome-web-security-stdout-warning.jpg"
  alt="chromeWebSecurity warning in stdout"
/>

If you rely on disabling web security, you will not be able to run tests on
browsers that do not support this feature.

:::

### Set `chromeWebSecurity` to `false`

Setting `chromeWebSecurity` to `false` in Chrome-based browsers allows you to do
the following:

- Display insecure content
- Navigate to any origin without cross-origin errors with or without
  `cy.origin`
- Access cross-origin iframes that are embedded in your application

Still here? That's cool, let's disable web security!

#### Set `chromeWebSecurity` to `false` in the [Cypress configuration](/app/references/configuration)

:::cypress-config-example

```ts
{
  chromeWebSecurity: false,
}
```

:::

## Modifying Obstructive Third Party Code

Cypress today has the concept of
[modifying obstructive code](/app/references/configuration#modifyObstructiveCode),
which is code that may interfere with Cypress being able to run your web
application. The `experimentalModifyObstructiveThirdPartyCode` flag provides the
same benefits of the
[modifyObstructiveCode](/app/references/configuration#modifyObstructiveCode)
flag, but additionally applies it to third-party `.js` and `.html` that is being
either loaded or navigated to inside your application. In addition to this, this
flag also does the following:

- Adjusts the User Agent in Electron to appear more chrome-like. This option can
  be overridden with the [userAgent](/app/references/configuration#Browser)
  config option.
- Removes
  [Subresource Integrity (SRI)](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)
  from modified scripts as they will not execute otherwise.
- Updates the `Sec-Fetch-Dest` Metadata header from `iframe` to `document` in
  cases where requests come from the application under test.

Want to enable `experimentalModifyObstructiveThirdPartyCode`? Let's do it!

:::cypress-config-example

```js
{
  experimentalModifyObstructiveThirdPartyCode: true
}
```

:::

## Other workarounds

There are other ways of testing the interaction between two origins. The
browser has a natural security barrier called `origin policy` this means that
state like `localStorage`, `cookies`, `service workers` and many other APIs are
not shared between them anyways. Cypress does offer APIs around `localStorage`,
`sessionStorage`, and `cookies` that are not limited to this restriction.

As a best practice, you should not visit or interact with any website not under
your control.

If your organization uses Single Sign On (SSO) or OAuth then you might choose to
test a 3rd party service other than your origin, which can be tested with
[`cy.origin()`](/api/commands/origin).

We've written several other guides specifically about handling this situation.

- [Best Practices: Visiting external sites](/app/core-concepts/best-practices#Visiting-External-Sites)
- [Recipes: Logging In - Single Sign On](/app/references/recipes#Logging-In)
- [Guides: Amazon Cognito Authentication](/app/guides/authentication-testing/amazon-cognito-authentication)
- [Guides: Auth0 Authentication](/app/guides/authentication-testing/auth0-authentication)
- [Guides: Okta Authentication](/app/guides/authentication-testing/okta-authentication)
